
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
from flask import Blueprint, Response

from lj_api import tool_flask
from lj_tool import tool_open_cv
api_rstp_stream = Blueprint('rstp_stream', __name__)


def generate_frames(rtsp_url):
    print(rtsp_url)
    if not rtsp_url:
        return

    # 打开 RTSP 流
    cap = cv2.VideoCapture(rtsp_url)

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # 在这里进行您想要的处理，例如图像预处理或添加水印等
        if tool_open_cv.is_gray_screen(frame):
            print("灰度图像...")
            continue

        # 将帧转换为 JPEG 图像
        ret, buffer = cv2.imencode('.jpg', frame)
        jpg_frame = buffer.tobytes()
        # 生成视频流
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + jpg_frame + b'\r\n')

    # 释放资源
    cap.release()


@api_rstp_stream.route('/stream_to_img')
def stream_to_img():
    print(123456)
    # res = Response(generate_frames(tool_flask.get_param("rtsp_url")),
    #                content_type='multipart/x-mixed-replace; boundary=frame')
    res = Response(generate_frames(tool_flask.get_param("rstp_url")),
                   mimetype='multipart/x-mixed-replace; boundary=frame')
    # res = Response(generate_frames(tool_flask.get_param("rtsp_url")))
    # res.headers['Content-Type'] = 'multipart/x-mixed-replace; boundary=frame'
    return res
